#!/usr/bin/env python
import MySQLdb
import types


class HandleMysql(object):
    def __init__(self,host,port,user,passwd,db):
        self.host=host
        self.port=int(port)
        self.user=user
        self.passwd=passwd
        self.db=db
        
    def connect(self):
        self.conn=MySQLdb.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db)
        self.cursor=self.conn.cursor()
        self.cursor.execute('set names utf8')
        
    def execute_sql(self,sql):
        self.sql=sql
        self.cursor.execute(self.sql)
        self.conn.commit()
        
    def insert_record(self,table,record):
        if type(record) is types.ListType:
            vs=','.join(['%s' for i in range(0,len(record))])
            self.cursor.execute("insert into "+table+" values ("+vs+")",record)
	    self.conn.commit()
	    #vs="','".join([str(rd) for rd in record])
            #self.execute_sql("insert into %s values ('%s')" % (table,vs))
        elif type(record) is types.DictType:
            ks=','.join([str(k) for k in record.keys()])
            vs=','.join(['%s' for i in range(0,len(record.values()))])
            self.cursor.execute("insert into "+table+" ("+ks+") values ("+vs+")",record.values())
            self.conn.commit()
        else:
            print 'The type of record must be list or dict!'
            return
        
    def update_record(self,table,record,condition):
        if type(record) is types.DictType:
            rs=','.join([str(r) for r in map(lambda s:'='.join([s,"'%s'"]),record.keys())])
            cs=' and '.join([str(c) for c in map(lambda s:'='.join([s,"'%s'"]),condition.keys())])
            tmp_list=[]
            map(lambda a:tmp_list.append(a),record.values())
            map(lambda a:tmp_list.append(a),condition.values())
            sql=("update "+table+" set "+rs+" where "+cs) % tuple(tmp_list)
            self.execute_sql(sql)
        else:
            print 'The type of record must be dict!'
            return
        
    def get_fields(self):
        return map(lambda a:a[0],self.cursor.description)
        
    def get_results(self,sql):
        self.execute_sql(sql)
        self.results=self.cursor.fetchall()
        return self.results
    
    def get_result(self,sql):
        self.execute_sql(sql)
        self.result=self.cursor.fetchone()
        return self.result[0]
    
    def get_cursor(self):
        return self.cursor
    
    def close(self):
        self.cursor.close()
        self.conn.close()
